﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace BBInterfaceNET.Events.Commands
{
    public class CommandReference:Freezable, ICommand
    {

        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new UIPropertyMetadata(null, OnCommandPropertyChanged));

        private static void OnCommandPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            CommandReference reference = o as CommandReference;
            ICommand oldVal = e.OldValue as ICommand;
            ICommand newVal = e.NewValue as ICommand;

            if (oldVal != null)
                oldVal.CanExecuteChanged -= reference.CanExecuteChanged;
            if (newVal != null)
                newVal.CanExecuteChanged += reference.CanExecuteChanged;
        }
        public bool CanExecute(object parameter)
        {
            if (Command != null)
                return Command.CanExecute(parameter);
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (Command != null)
                Command.Execute(parameter);
        }

        protected override Freezable CreateInstanceCore()
        {
            throw new NotImplementedException();
        }
    }
}
